@extends('admin.common.web')

@section('title','商品修改')
@section('content')
    <!-- Page Breadcrumb -->
    <div class="page-breadcrumbs">
        <ul class="breadcrumb">
            <li>
                <a href="{{ route('admin.index.index') }}">系统</a>
            </li>
            <li>
                <a href="{{ route('admin.goods.index') }}">商品管理</a>
            </li>
            <li class="active">修改商品</li>
        </ul>
    </div>
    <!-- /Page Breadcrumb -->

    <!-- Page Body -->
    <div class="page-body">

        <div class="row">
            <div class="col-lg-12 col-sm-12 col-xs-12">
                <div class="widget">
                    <form class="form-horizontal" role="form" action="{{ route('admin.goods.update',['id'=>$goods['id']]) }}" onsubmit="return false" method="post" enctype="multipart/form-data">
                        @csrf
                        <div class="widget-body">
                            <div class="widget-main ">
                                <div class="tabbable">
                                    <ul class="nav nav-tabs tabs-flat" id="myTab11">
                                        <li class="active">
                                            <a data-toggle="tab" href="#home11">
                                                基本信息
                                            </a>
                                        </li>
                                        <li class="">
                                            <a data-toggle="tab" href="#profile11">
                                                商品描述
                                            </a>
                                        </li>
                                        <li class="">
                                            <a data-toggle="tab" href="#profile12">
                                                商品属性
                                            </a>
                                        </li>
                                        {{--<li class="">
                                            <a data-toggle="tab" href="#profile13">
                                                商品类型
                                            </a>
                                        </li>--}}
                                        <li class="">
                                            <a data-toggle="tab" href="#profile14">
                                                商品相册
                                            </a>
                                        </li>
                                    </ul>
                                    <div class="tab-content tabs-flat">
                                        <div id="home11" class="tab-pane active">
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">商品名</label>
                                                <div class="col-sm-6">
                                                    <input class="form-control" name="goods_name" value="{{ $goods->goods_name }}" required="" type="text">
                                                </div>
                                                <p class="help-block col-sm-4 red">* 必填</p>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">商品图片</label>
                                                <img src="{{ asset($goods['thumb']) }}" width="30" height="30" alt=""/>
                                                <div class="col-sm-6">
                                                    <input name="thumb" type="file">
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">商品分类</label>
                                                <div class="col-sm-6">
                                                    <select name="category_id" required>
                                                        @foreach($category as $vo)
															<?php
															if ($vo['level'] > 0) {
																$str = str_repeat('---', $vo['level']);
															} else {
																$str = '';
															}
															?>
                                                            <option value="{{ $vo['id'] }}" @if($goods['category_id'] == $vo['id']) selected @endif><?=$str;?>{{ $vo['category_name'] }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                <p class="help-block col-sm-4 red">* 必填（请选择小分类）</p>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">商品品牌</label>
                                                <div class="col-sm-6">
                                                    <select name="brand_id" required>
                                                        <option value="">请选择品牌</option>
                                                        @foreach($brand as $vo)
                                                            <option value="{{ $vo['id'] }}" @if($goods['brand_id'] == $vo['id']) selected @endif>{{ $vo['brand_name'] }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                <p class="help-block col-sm-4 red">* 必填</p>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">商品状态</label>
                                                <div class="col-sm-6">
                                                    <div class="radio" style="float: left;padding-right: 10px;">
                                                        <label>
                                                            <input name="status" type="radio" @if($goods['status'] == 1) checked="checked" @endif value="1">
                                                            <span class="text">上架 </span>
                                                        </label>
                                                    </div>
                                                    <div class="radio" style="float: left;">
                                                        <label>
                                                            <input name="status" type="radio" @if($goods['status'] == 0) checked="checked" @endif value="0">
                                                            <span class="text">下架</span>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">商品排序</label>
                                                <div class="col-sm-6">
                                                    <input class="form-control" name="sort" required="" value="{{ $goods->sort }}" type="text">
                                                </div>
                                            </div>
                                        </div>

                                        <div id="profile11" class="tab-pane">
                                            <textarea id="container" name="description">{{ $goods->description }}</textarea>
                                        </div>

                                        <div id="profile12" class="tab-pane">
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">商品类型</label>
                                                <div class="col-sm-6">
                                                    <select disabled>
                                                        @foreach($typeList as $vo)
                                                            <option value="{{ $vo['id'] }}" @if($vo['id'] == $goods['type_id']) selected @endif>{{ $vo['type_name'] }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                            <div id="spec">
                                                @foreach($spec as $v)
                                                    <div class="form-group">
                                                        <label for="inputEmail3" class="col-sm-1 control-label no-padding-right">
                                                            {{ $v['spec_name'] }}
                                                            <input type="hidden" value="spec[{{ $v['id'] }}]">
                                                        </label>
                                                        <div class="col-sm-11">
                                                            @foreach($v['spec_value'] as $spec_child)
                                                                <label>
                                                                    <input type="checkbox" name="spec[{{ $v['id'] }}][]" @if(in_array($spec_child['id'],$goodsSpecArr)) checked @endif value="{{ $spec_child['id'] }}">
                                                                    <span class="text">{{ $spec_child['value'] }}</span>
                                                                </label>
                                                            @endforeach
                                                        </div>
                                                    </div>
                                                @endforeach
                                            </div>
                                            <div id="stock">
                                                {{--库存--}}
                                                <table class="table table-hover table-striped table-bordered">
                                                    <tbody>
                                                    @foreach($skuSpecInfo as $k => $v)
                                                        <tr>
                                                            @foreach($v as $k1 => $v1)
                                                                <td>{{ $v1['value'] }}</td>
                                                            @endforeach
                                                            <td>
                                                                <input type="hidden" name="sku[]" value="{{ $goods_sku[$k]['sku_list'] }}">
                                                                <input type="number" placeholder="请输入库存" value="{{ $goods_sku[$k]['inventory'] }}" name="sku_num[]">
                                                            </td>
                                                            <td>
                                                                <input type="text" placeholder="输入价格" value="{{ $goods_sku[$k]['price'] }}" oninput="checkPrice(this,1,9999999)" onblur="checkPrice(this,2,9999999)" name="sku_price[]">
                                                            </td>
                                                        </tr>
                                                    @endforeach
                                                    </tbody>
                                                </table>
                                            </div>

                                        </div>

                                        <!--<div id="profile13" class="tab-pane">
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">商品类型</label>
                                                <div class="col-sm-6">
                                                </div>
                                            </div>
                                            <div id="attr_list">
                                                <div class="form-group">
                                                    <label class="col-sm-2 control-label no-padding-right">颜色</label>
                                                    <div class="col-sm-6">
                                                        <a href="javascript:void(0);">[+]</a>
                                                        <select name="goods_weight">
                                                            <option value="kg">蓝色</option>
                                                            <option value="kg">黄色</option>
                                                        </select>
                                                        <input class="form-control" name="brand_name" style="width:150px;display: inline-block;box-shadow: none" type="text">
                                                    </div>
                                                </div>

                                                <div class="form-group">
                                                    <label class="col-sm-2 control-label no-padding-right">颜色</label>
                                                    <div class="col-sm-6">
                                                        <select name="goods_weight">
                                                            <option value="kg">蓝色</option>
                                                            <option value="kg">黄色</option>
                                                        </select>
                                                    </div>
                                                </div>

                                                <div class="form-group">
                                                    <label class="col-sm-2 control-label no-padding-right">材质</label>
                                                    <div class="col-sm-6">
                                                        <input class="form-control" name="brand_name" style="width:150px;display: inline-block;box-shadow: none" type="text">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>-->
                                        <div id="profile14" class="tab-pane">
											<?php if($goods_album):?>
                                            <div class="form-group">
                                                <div class="col-sm-6">
                                                    <ul style="display: flex;text-align: center;list-style: none">
														<?php foreach($goods_album as $k=>$v):?>
                                                            <li style="margin-left: 3px" class="album">
                                                            <img src="{{ $v['image'] }}" width="80" height="80" alt=""/>
                                                                <br/>
                                                                <a style="margin-top: 3px" href="javascript:void(0);" onclick="deleteImg(this,{{ $v['id'] }})" class="btn btn-sm btn-default">删除</a>
                                                            </li>
														<?php endforeach;?>
                                                    </ul>

                                                </div>
                                            </div>

                                            <div class="form-group album_file_item" @if(count($goods_album) == 5) hidden @endif>
                                                <div class="col-sm-6">
                                                    <a style="float: left;padding-right: 5px" onclick="cloneMe(this)" href="javascript:void(0);">[+]</a>
                                                    <input name="album[]" type="file">
                                                </div>
                                            </div>

											<?php else:?>
                                                <div class="form-group album_file_item">
                                                    <div class="col-sm-6">
                                                        <a style="float: left;padding-right: 5px" onclick="cloneMe(this)" href="javascript:void(0);">[+]</a>
                                                        <input name="album[]" type="file">
                                                    </div>
                                                </div>
											<?php endif;?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-10">
                                    {{--<button type="submit" id="submit_btn" class="btn btn-default">保存信息</button>--}}
                                    <button id="submit_btn" class="btn btn-info">保存信息</button>
                                    <a href="JavaScript:window.history.go(-1);" class="btn btn-default">返回</a>
                                </div>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>

    </div>
    <!-- /Page Body -->
@endsection

@section('script')
    <script type="text/javascript" src="{{  asset('js/api_request.js') }}"></script>
    <script type="text/javascript" src="{{  asset('js/common.js') }}"></script>

    <script type="text/javascript" src="{{  asset('plugins/ueditor/1.4.3/ueditor.config.js') }}"></script>
    <!-- 编辑器源码文件 -->
    <script type="text/javascript" src="{{  asset('plugins/ueditor/1.4.3/ueditor.all.js') }}"></script>
    <script type="text/javascript" src="{{  asset('plugins/ueditor/1.4.3/lang/zh-cn/zh-cn.js') }}"></script>
    <!-- 实例化编辑器 -->

    <script>
        $(() => {
            /**
             *  实例化编辑器
             * */
            var ue = UE.getEditor('container', {
                toolbars: [
                    ['fullscreen', 'source', '|', 'undo', 'redo', '|',
                        'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                        'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                        'directionalityltr', 'directionalityrtl', 'indent', '|',
                        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                        'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                        'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
                        'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
                        'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
                        'print', 'preview', 'searchreplace', 'drafts', 'help']
                ],
                initialFrameHeight: 320,
                autoHeightEnabled: true,
                autoFloatEnabled: true
            });

            //展示分类下的规格
            /*$('select[name="category_id"]').change(async function () {
                let category_id = $(this).val();

                await requestData('route("admin.goods.ajaxGetSpec")', {'category_id': category_id}).then((res) => {
                    let html = '';
                    $.each(res.data, function (k, v) {
                        html += '<div class="form-group">';
                        html += '<label class="col-sm-1 control-label no-padding-right">';
                        html += '<input name="spec[' + v.id + ']" type="hidden">' + v.spec_name;
                        html += '</label>';

                        html += '<div class="col-sm-11">';

                        $.each(v.spec_value, function (k1, v1) {
                            html += '<label>';
                            html += '<input type="checkbox" class="spec_ids" name="spec[' + v.id + '][]" value="' + v1.id + '">';
                            html += '<span class="text">' + v1.value + '</span>';
                            html += '</label>';
                        });
                        html += '</div>';
                        html += '</div>';
                    });

                    $('#spec').html('');
                    $('#stock').html('');
                    $('#spec').append(html);
                }).catch((res) => {
                    $('#spec').html('');
                    $('#stock').html('');
                })
            })*/

            //异步提交数据
            $('#submit_btn').click(async function () {
                $(this).prop('disabld', true);
                let data = new FormData($('form')[0]);

                await formRequest('{{ route("admin.goods.update",['id'=>$goods['id']]) }}', data, 'post').then((res) => {
                    layer.msg(res.msg);
                    setTimeout(()=>{
                        window.location.href = '{{ route('admin.goods.index') }}';
                    },500);
                }).catch((res) => {
                    layer.msg(res.msg);
                    $(this).prop('disabld', false);
                });

                return false;
            })
        });


        //库存表格
        $('#spec').on('click', 'input', function () {
            let ipt = $('#spec input[type="checkbox"]:checked');
            let ids = [];
            $.each(ipt, function (k, v) {
                ids.push($(this).val());
            });

            requestData('{{ route("admin.goods.ajaxGetStockDicar") }}', {"ids": JSON.stringify(ids)}, 'post').then((res) => {
                $('#stock').html('');

                let html = '';
                html += '<table class="table table-hover table-striped table-bordered">';
                html += '<tbody>';

                $.each(res.data, function (k, v) {
                    html += '<tr>';
                    //如果的单种规格属性的 例如只有颜色 没有其他
                    let sku_ids = [];
                    if (typeof v == 'string') {
                        html += '<td>' + v + '</td>';
                        sku_ids.push(k);
                    } else {
                        //多个规格的
                        $.each(v, function (k1, v1) {
                            html += '<td>' + v1 + '</td>';
                            sku_ids.push(k1);
                        })
                    }
                    html += '<td>';
                    html += '<input type="hidden" name="sku[]" value="' + sku_ids.join(',') + '">';
                    html += '库存：<input type="number" placeholder="请输入库存" sku_list="' + sku_ids.join(',') + '" name="sku_num[]">';
                    html += '</td>';

                    html += '<td>';
                    html += '价格：<input type="text" placeholder="输入价格" sku_list="' + sku_ids.join(',') + '" oninput="checkPrice(this,1,9999999)" onblur="checkPrice(this,2,9999999)" name="sku_price[]">';
                    html += '</td>';
                    html += '</tr>';
                })
                html += '</tbody>';
                html += '</table>';

                getExistsInventory();

                $('#stock').append(html);
            }).catch((res) => {
                $('#stock').html('');
            })
        });


        //当库存的dom节点改变后，将最新的库存数据从新读入并写入库存
        function getExistsInventory() {
            let inventoryList = <?= json_encode($sku_str) ?>;
            console.log(inventoryList);

            let goods_id = '{{ $goods["id"] }}';
            $.each(inventoryList, async function (k, v) {
                console.log(k);
                console.log(v);

                await requestData('{{ route("admin.goods.ajaxGetNowInventory") }}', {
                    "goods_id": goods_id,
                    "sku_list": v
                }).then((res) => {
                    let skuNumberDom = $('input[name="sku_num[]"][sku_list="' + v + '"]');
                    let skuPriceDom = $('input[name="sku_price[]"][sku_list="' + v + '"]');

                    console.log(skuNumberDom);
                    $(skuNumberDom).prop('value', res.data.inventory);
                    $(skuPriceDom).prop('value', res.data.price);
                });
            })
        }

        /**
         * 克隆节点
         * @param btn
         */
        function cloneMe(btn) {
            let mybtn = $(btn);
            let item = $(mybtn).parent().parent('.form-group');

            let album_file_item = $('#profile14 .album_file_item');

            let album_count = $('.album');

            let allow_len = 5 - (parseInt(album_file_item.length) + parseInt(album_count.length));

            if (mybtn.html() == '[+]') {

                if(allow_len <= 0){
                    layer.msg('不能再添加了');
                    return false;
                }

                let newItem = item.clone();
                newItem.find('a').html('[-]');

                item.after(newItem);
            } else {
                item.remove();
            }
        }

        /**
         * 删除相册图片
         * @param btn
         * @param id
         */
        function deleteImg(btn, id) {
            if(confirm('确定要删除吗？')){
                requestData('{{ route("admin.goods.ajaxDeleteImage") }}',{"id":id}).then((res)=>{
                    layer.msg(res.msg);
                    $(btn).parent('li').remove();

                    let album_count = $('.album');

                    if(album_count.length < 5){
                        $('.album_file_item').show();
                    }
                }).catch((res)=>{
                    layer.msg(res.msg);
                })
            }
        }

    </script>
@endsection
